package com.fjec.im.service.impl;

import com.fjec.common.aliyun.sms.AliyunSmsHelper;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.SmsException;
import com.fjec.im.service.ICommonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class CommonServiceImpl implements ICommonService {

    @Value("${user.sms.signName}")
    private String signName;

    @Value("${user.sms.newOrderTempCode}")
    private String newOrderTempCode;

    @Value("${user.sms.remindDeliverTempCode}")
    private String remindDeliverTempCode;

    @Resource
    private AliyunSmsHelper aliyunSmsHelper;

    @Override
    public void sendNewOrder(String phoneNum) {
        HashMap<String, String> param = new HashMap<>();
        this.sendMsg(phoneNum, signName, newOrderTempCode, param);
    }

    @Override
    public void sendRemindDeliver(String phoneNum) {
        HashMap<String, String> param = new HashMap<>();
        this.sendMsg(phoneNum, signName, remindDeliverTempCode, param);
    }

    /**
     * 发送短信
     *
     * @param phoneNum
     * @param signName
     * @param tempCode
     * @param param
     */
    private void sendMsg(String phoneNum, String signName, String tempCode, Map<String, String> param) {
        try {
            Map<String, Object> result = aliyunSmsHelper.sendSms(phoneNum, signName, tempCode, param);
            if (!Objects.equals("OK", MapUtils.getString(result, "Code"))) {
                throw new SmsException(EnumSysCode.ERR_0029.getCode(), MapUtils.getString(result, "Message"));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new SmsException(EnumSysCode.ERR_3012.getCode(), e.getMessage());
        }
    }
}
